// Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license.
package com.linqingying.gitcode.pullrequest.data

import com.intellij.openapi.progress.ProgressIndicator
import com.intellij.openapi.progress.ProgressManager
import com.linqingying.gitcode.api.GCGQLRequests
import com.linqingying.gitcode.api.GCRepositoryCoordinates
import com.linqingying.gitcode.api.GCRepositoryPath
import com.linqingying.gitcode.api.GitCodeApiRequestExecutor
import com.linqingying.gitcode.api.data.pullrequest.GCPullRequestShort
import com.linqingying.gitcode.api.data.request.search.GitCodeIssueSearchType
import com.linqingying.gitcode.api.util.GitCodeApiSearchQueryBuilder
import com.linqingying.gitcode.api.util.SimpleGCGQLPagesLoader
import kotlin.properties.Delegates

internal class GCPRListLoader(
  progressManager: ProgressManager,
  requestExecutor: GitCodeApiRequestExecutor,
  repository: GCRepositoryCoordinates,
) : GCListLoaderBase<GCPullRequestShort>(progressManager) {

  var searchQuery by Delegates.observable<GCPRSearchQuery?>(null) { _, _, _ ->
    reset()
  }

  private val loader = SimpleGCGQLPagesLoader(requestExecutor, { p ->
    GCGQLRequests.PullRequest.search(repository.serverPath, buildQuery(repository.repositoryPath, searchQuery), p)
  }, pageSize = 50)

  override fun canLoadMore() = !loading && loader.hasNext && error == null

  override fun doLoadMore(indicator: ProgressIndicator, update: Boolean) = loader.loadNext(indicator, update)

  override fun reset() {
    loader.reset()
    super.reset()
  }

  companion object {
    private fun buildQuery(repoPath: GCRepositoryPath, searchQuery: GCPRSearchQuery?): String {
      return GitCodeApiSearchQueryBuilder.searchQuery {
        term(GCPRSearchQuery.QualifierName.type.createTerm(GitCodeIssueSearchType.pr.name))
        term(GCPRSearchQuery.QualifierName.repo.createTerm(repoPath.toString()))
        if (searchQuery != null) {
          for (term in searchQuery.terms) {
            this.term(term)
          }
        }
      }
    }
  }
}
